Billdesk Payment

  • Package Installation

    Prerequirement

    1. Billdesk API endpoint

    2. Billdesk Client ID

    3. Billdesk Merchant ID

    4. Billdesk Secret

    5. Application returnURL

    6. Application webhookURL

    2. in controller

    
    
    $api_url ="https://api.billdesk.com/payments/ve1_2/orders/create";
    $clientId="xxxxxxx";
    $merchantId="xxxxxxxx";
    $secret="xxxxxxxxxx";
    $returnUrl="https://mydomain.com/payment/callback";
    
    class JWT
    {
        /**
         * @param  string      $jwt    The JWT
         * @param  string|null $key    The secret key
         * @param  bool        $verify Don't skip verification process 
         *
         * @return  object The JWT's payload as a PHP object
         */
        public static function decode($jwt, $key = null, $verify = true)
        {
            $tks = explode('.', $jwt);
            if (count($tks) != 3) {
                throw new Exception('Wrong number of segments');
            }
            list($headb64, $payloadb64, $cryptob64) = $tks;
            if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))
            ) {
                throw new Exception('Invalid segment encoding');
            }
            if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($payloadb64))
            ) {
                throw new Exception('Invalid segment encoding');
            }
            $sig = JWT::urlsafeB64Decode($cryptob64);
            if ($verify) {
                if (empty($header->alg)) {
                    throw new Exception('Empty algorithm');
                }
                if ($sig != JWT::sign("$headb64.$payloadb64", $key, $header->alg)) {
                    throw new Exception('Signature verification failed');
                }
            }
            return $payload;
        }
        /**
         * @param  object|array $payload PHP object or array
         * @param  string       $key     The secret key
         * @param  string       $algo    The signing algorithm
         *
         * @return  string A JWT
         */
        public static function encode($payload, $key, $algo = 'HS256',$head)
        {
            $header = array('typ' => 'JWT', 'alg' => $algo);
             if (isset($head) && is_array($head)) {
                $header = array_merge($head, $header);
            }
            $segments = array();
            $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
            $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
            $signing_input = implode('.', $segments);
            $signature = JWT::sign($signing_input, $key, $algo);
            $segments[] = JWT::urlsafeB64Encode($signature);
            return implode('.', $segments);
        }
        /**
         * @param  string $msg    The message to sign
         * @param  string $key    The secret key
         * @param  string $method The signing algorithm
         *
         * @return  string An encrypted message
         */
        public static function sign($msg, $key, $method = 'HS256')
        {
            $methods = array(
                'HS256' => 'sha256',
                'HS384' => 'sha384',
                'HS512' => 'sha512',
            );
            if (empty($methods[$method])) {
                throw new Exception('Algorithm not supported');
            }
            return hash_hmac($methods[$method], $msg, $key, true);
        }
        /**
         * @param  string $input JSON string
         *
         * @return  object Object representation of JSON string
         */
        public static function jsonDecode($input)
        {
            $obj = json_decode($input);
            if (function_exists('json_last_error') && $errno = json_last_error()) {
                JWT::handleJsonError($errno);
            }
            else if ($obj === null && $input !== 'null') {
                throw new DomainException('Null result with non-null input');
            }
            return $obj;
        }
        /**
         * @param  object|array $input A PHP object or array
         *
         * @return  string JSON representation of the PHP object or array
         */
        public static function jsonEncode($input)
        {
            $json = json_encode($input);
            if (function_exists('json_last_error') && $errno = json_last_error()) {
                JWT::handleJsonError($errno);
            }
            else if ($json === 'null' && $input !== null) {
                throw new Exception('Null result with non-null input');
            }
            return $json;
        }
        /**
         * @param  string $input A base64 encoded string
         *
         * @return  string A decoded string
         */
        public static function urlsafeB64Decode($input)
        {
            $remainder = strlen($input) % 4;
            if ($remainder) {
                $padlen = 4 - $remainder;
                $input .= str_repeat('=', $padlen);
            }
            return base64_decode(strtr($input, '-_', '+/'));
        }
        /**
         * @param  string $input Anything really
         *
         * @return  string The base64 encode of what you passed in
         */
        public static function urlsafeB64Encode($input)
        {
            return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
        }
        /**
         * @param  int $errno An error number from json_last_error()
         *
         * @return  void
         */
        private static function handleJsonError($errno)
        {
            $messages = array(
                JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
                JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
                JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
            );
            throw new Exception(isset($messages[$errno])
                ? $messages[$errno]
                : 'Unknown JSON error: ' . $errno
            );
        }
    }
    
    
    
    date_default_timezone_set('Asia/Calcutta');
    echo date_default_timezone_get();
    
    
    
    $headers = array(
            "alg" => "HS256",
            "clientid" =>$clientId,
            "kid" => "HMAC"
    );
    $trace_id = "cashewcapex".rand();
    $servertime =time();
    $data['amount']=300;
    
    $payload                        = array();
    $payload['orderid']             = $trace_id;
    $payload['mercid']              = $merchantId;
    echo $payload['order_date']          = date("Y-m-d\TH:i:s\+05:30");
    $payload['amount']              = number_format((float)$data['amount'], 2, '.', '');
    $payload['currency']            ='356';
    $payload['ru'] 	           = $returnUrl ;// Return URL
                
    
         $payload['additional_info']    =  array(
                                                     "additional_info1" =>"Online Shopping Cart",
                                                    "additional_info2" => "manojvijayanaluva@gmail.com",
                                                    "additional_info3" => "9847483390",
                                                    "additional_info4" => "mano",
                                                    "additional_info5" => "NA",
                                                    "additional_info6" => "NA",
                                                    "additional_info7" => "NA",
                                          );
    
         $payload['itemcode']           = 'DIRECT';
         $payload['device']             =  array(
                                                   "init_channel" => "internet",
                                                   "ip" => $_SERVER['REMOTE_ADDR'],
                                                   "user_agent"    => $_SERVER['HTTP_USER_AGENT'],
                                                   "accept_header" => "text/html",
                                               );
    
                                               echo '<br>*******************REQUESTED PAYLOADS**************************<br>';
                                               print_r($payload);
                                               echo '<br>*******************END REQUESTED PAYLOADS**************************<br>';
         /*****************************************/
                 // Encode payload
         /*****************************************/
         echo '<br>*******************REQUESTED ENCODED STRING**************************<br>';
         echo $curl_payload = JWT::encode($payload, $secret, "HS256",$headers);
         echo '<br>*******************END REQUESTED ENCODED STRING**************************<br>';
    
    
    
    
         $ch = curl_init( $api_url );
         $ch_headers = array(
                 "Content-Type: application/jose",
                 "accept: application/jose",
                 "bd-traceid:$trace_id",
                 "bd-timestamp:$servertime"
         );
    
         echo '<br>*******************REQUESTED HEADER**************************<br>';
         print_r( $ch_headers);
         echo '<br>*******************END REQUESTED HEADER**************************<br>';
    
         curl_setopt( $ch, CURLOPT_HTTPHEADER, $ch_headers);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt( $ch, CURLOPT_POSTFIELDS, $curl_payload);
         curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );					
         $response = curl_exec($ch);
    
         //print_r( $response);exit;
    
    
         $result_decoded = JWT::decode($response, $secret, 'HS256');
         $result_array = (array) $result_decoded;
    
        print_r( $result_array);
    
         if ($result_decoded->status == 'ACTIVE') {
                 $transactionid = $result_array['links'][1]->parameters->bdorderid;
                 $authtoken = $result_array['links'][1]->headers->authorization;
                 $requestParams['order_id'] = $result_decoded->orderid;
                 $requestParams['transactionid'] = $transactionid;
                 $requestParams['authtoken'] = $authtoken;
                 $requestParams;
    
                 print_r($requestParams);
         }
         else {
               echo $result_decoded->status;
         }
    
    
        

    3. in html

    
    
        <script type="module" src="https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.esm.js"></script>
        <script nomodule="" src="https://pay.billdesk.com/jssdk/v1/dist/billdesksdk.js"></script>
        <link href="https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.css" rel="stylesheet">
    
    
        <script>
            var flow_config = {
                merchantId: "{{$merchantId}}",
                bdOrderId: "{{$transactionid}}",
                authToken: "{{$authToken}}",
                childWindow: false,
                returnUrl: "{{$returnUrl}}",
                retryCount: 0
            };
            var responseHandler = function(txn) {
                if (txn.response) {
                    alert("callback received status:: ", txn.status);
                    alert("callback received response:: ", txn.response)//response handler to be implemented by the merchant
                }
            };
            var config = {
                flowConfig: flow_config,
                flowType: "payments"
            };
            window.onload = function() {
                setTimeout(function() {
                    window.loadBillDeskSdk(config);
                }, 1500);
            };
        </script>